//
//  LaunchSOSView.m
//  location
//
//  Created by Dongxiang Xu on 2025/8/27.
//

#import "LaunchSOSView.h"
#import "UIImageView+WebCache.h"

@interface LaunchSOSView ()

@property(nonatomic,strong) UIView *wave;
@property(nonatomic,strong) UIView *aWave;
@property(nonatomic,strong) UILabel *sos;

@end

@implementation LaunchSOSView

- (instancetype)initWithFrame:(CGRect)frame
                    GroupInfo:(NSDictionary *)groupInfo
                       
{
    self = [super initWithFrame:frame];
    if (self) {       
        UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        bg.backgroundColor = [RealBlackColor colorWithAlphaComponent:0.4];
        bg.alpha = 0;
        [self addSubview:bg];
        
        _sos = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-145)/2, (SCREEN_HEIGHT-290-144)/2, 144, 144)];
        _sos.layer.masksToBounds = YES;
        [_sos.layer setCornerRadius:72];
        _sos.backgroundColor = SOSColor;
        _sos.textColor = RealWhiteColor;
        _sos.font = MEDIUM_FONT(48);
        _sos.textAlignment = NSTextAlignmentCenter;
        _sos.text = @"SOS";
        [bg addSubview:_sos];
        
        _wave = [[UIView alloc] initWithFrame:CGRectMake(_sos.x, _sos.y, _sos.width, _sos.height)];
        _wave.backgroundColor = SOSColor;
        _wave.layer.masksToBounds = YES;
        [_wave.layer setCornerRadius:_wave.width/2];
        [bg insertSubview:_wave belowSubview:_sos];
                
        _aWave = [[UIView alloc] initWithFrame:CGRectMake(_sos.x, _sos.y, _sos.width, _sos.height)];
        _aWave.backgroundColor = SOSColor;
        _aWave.layer.masksToBounds = YES;
        [_aWave.layer setCornerRadius:_aWave.width/2];
        [bg insertSubview:_aWave belowSubview:_sos];
        
        UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(8, SCREEN_HEIGHT, SCREEN_WIDTH-16, 190)];
        infoView.layer.masksToBounds = YES;
        [infoView.layer setCornerRadius:13];
        [self addSubview:infoView];
        
        UIVisualEffectView *visualEffect = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
        visualEffect.frame = CGRectMake(0, 0, infoView.width, infoView.height);
        [infoView addSubview:visualEffect];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 12, infoView.width, 24)];
        title.font = MEDIUM_FONT(20);
        title.textAlignment = NSTextAlignmentCenter;
        title.textColor = GraryHeavyLightColor;
        title.text = @"遇到紧急情况了？";
        [infoView addSubview:title];
        
        UIView *avatarView = [[UIView alloc] initWithFrame:CGRectMake(0, title.maxY+24, 0, 32)];
        [infoView addSubview:avatarView];
        
         
        if (groupInfo[@"userInfo"] && [groupInfo[@"userInfo"] count]>0) {
            for (int i = 0; i < [groupInfo[@"userInfo"] count]; i ++) {
                UIImageView *avatar = [[UIImageView alloc] initWithFrame:CGRectMake(i*27, 0, 32, 32)];
                avatar.backgroundColor = GraryMiddleColor ;
                avatar.layer.masksToBounds = YES;
                [avatar.layer setCornerRadius:16];
                [avatar.layer setBorderWidth:1];
                [avatar.layer setBorderColor:RealWhiteColor.CGColor];
                [avatar sd_setImageWithURL:[NSURL URLWithString:groupInfo[@"userInfo"][i][@"avatar"]]];
                [avatarView addSubview:avatar];
                
                if (i==([groupInfo[@"userInfo"] count]-1)) {
                    [avatarView setFrame:CGRectMake((infoView.width-avatar.maxX)/2, title.maxY+24, avatar.maxX, 32)];
                }
            }
        }
        
        
        UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, avatarView.maxY+10, infoView.width, 18)];
        subTitle.font = DEFAULT_FONT(14);
        subTitle.textAlignment = NSTextAlignmentCenter;
        subTitle.textColor = [GraryHeavyLightColor colorWithAlphaComponent:0.6];
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"你的 SOS 将发送给这 %lu 个人",(unsigned long)[groupInfo[@"userInfo"] count]]];
        [str addAttribute:NSFontAttributeName value:RUBIK_BOLD_FONT(14) range:NSMakeRange(3, 3)];
        [str addAttribute:NSFontAttributeName value:RUBIK_BOLD_FONT(14) range:NSMakeRange(13, [NSString stringWithFormat:@"%lu",(unsigned long)[groupInfo[@"userInfo"] count]].length)];
        subTitle.attributedText = str;
        [infoView addSubview:subTitle];
        
        UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, subTitle.maxY+12, infoView.width, 1)];
        line.image = [UIImage imageNamed:@"line"];
        [infoView addSubview:line];
        
        UIButton *sosButton = [[UIButton alloc] initWithFrame:CGRectMake(0, line.maxY, infoView.width, infoView.height-line.maxY)];
        [sosButton setTitle:@"立即呼救" forState:UIControlStateNormal];
        [sosButton setTitleColor:RedColor forState:UIControlStateNormal];
        [sosButton.titleLabel setFont:REAL_MEDIUM_FONT(20)];
        [infoView addSubview:sosButton];
                
        UIButton *close = [[UIButton alloc] initWithFrame:CGRectMake(infoView.x, infoView.maxY+8, infoView.width, 60)];
        close.backgroundColor = RealWhiteColor;
        close.layer.masksToBounds = YES;
        [close.layer setCornerRadius:13];
        close.titleLabel.font = MEDIUM_FONT(20);
        [close setTitleColor:[GraryHeavyLightColor colorWithAlphaComponent:0.6] forState:UIControlStateNormal];
        [close setTitle:@"关闭" forState:UIControlStateNormal];
        [self addSubview:close];
        [[close rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [UIView animateWithDuration:0.3 animations:^{
                infoView.y = SCREEN_HEIGHT;
                close.y = infoView.maxY+8;
                bg.alpha = 0;
            } completion:^(BOOL finished) {
                [self removeFromSuperview];
            }];
        }];
        
        [[sosButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            // 先请求http，让后端发送push
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            manager.requestSerializer.timeoutInterval = 10;
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:groupInfo[@"id"] forKey:@"groupId"];
            [manager GET:[NSString stringWithFormat:@"%@/apps/data/sosnotification",NETURL] parameters:param headers:@{@"Authorization":[XDXShareInstance shareInstance].access_token} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                  
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

            }];
            
            [UIView animateWithDuration:0.3 animations:^{
                infoView.y = SCREEN_HEIGHT;
                close.y = infoView.maxY+8;
                bg.alpha = 0;
            } completion:^(BOOL finished) {
                [self removeFromSuperview];
            }];
            
            // 再通过block发送socket和更新UI
            if (self.LaunchSOSBlock) {
                self.LaunchSOSBlock();
            }
        }];
        
        [UIView animateWithDuration:0.3 animations:^{
            infoView.y = SCREEN_HEIGHT-290;
            close.y = infoView.maxY+8;
            bg.alpha = 1;
        }];
        
        [self waveAnimation];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self aWaveAnimation];
        });
    }
    return self;
}

- (void)waveAnimation
{
    if (self) {
        [UIView animateWithDuration:2 animations:^{
            [self.wave setFrame:CGRectMake(self.sos.x-44, self.sos.y-44, self.sos.width+88, self.sos.height+88)];
            self.wave.alpha = 0;
            [self.wave.layer setCornerRadius:self.wave.width/2];
        } completion:^(BOOL finished) {
            [self.wave setFrame:CGRectMake(self.sos.x, self.sos.y, self.sos.width, self.sos.height)];
            [self.wave.layer setCornerRadius:self.wave.width/2];
            self.wave.alpha = 1;
            [self waveAnimation];
        }];
    }
}

- (void)aWaveAnimation
{
    if (self) {
        [UIView animateWithDuration:2 animations:^{
            [self.aWave setFrame:CGRectMake(self.sos.x-44, self.sos.y-44, self.sos.width+88, self.sos.height+88)];
            self.aWave.alpha = 0;
            [self.aWave.layer setCornerRadius:self.aWave.width/2];
        } completion:^(BOOL finished) {
            [self.aWave setFrame:CGRectMake(self.sos.x, self.sos.y, self.sos.width, self.sos.height)];
            [self.aWave.layer setCornerRadius:self.aWave.width/2];
            self.aWave.alpha = 1;
            [self aWaveAnimation];
        }];
    }
}

@end
